package nl.ru.rd.facedetection.nnbfd;

/**
 * A linear equalizer to be used in the preprocessor.
 * 
 * @author Christiaan Thijssen s0814970
 * @author Kevin Reintjes s0814954
 * @author Wouter Geraedts (s0814857 - wgeraedts) PGP 66AA5935
 * 
 */
public class LinearEqualizer
{

	final static int Levels = 256;

	/**
	 * Fits linear equalization to a Matrix.
	 * 
	 * @param matrix
	 *            The matrix to be equalized.
	 */
	public void equalize(Matrix matrix)
	{
		int height = matrix.getHeight();
		int width = matrix.getWidth();
		int correction = (int) this.calculateAverage(matrix) - Levels / 2 - 1;

		for(int y = 0; y < height; y++)
			for(int x = 0; x < width; x++)
			{
				int newvalue = matrix.getValue(x, y) - correction;
				if(newvalue > 255)
					newvalue = 255;
				else if(newvalue < 0)
					newvalue = 0;
				matrix.setValue(x, y, (short) (newvalue));
			}
	}

	private double calculateAverage(Matrix matrix)
	{
		int height = matrix.getHeight();
		int width = matrix.getWidth();
		int dimension = width * height;

		int totalValue = 0;
		for(int y = 0; y < height; y++)
			for(int x = 0; x < width; x++)
				totalValue += matrix.getValue(x, y);

		return (double) totalValue / (double) dimension;
	}
}
